package com.chuangke.framework.model;

import java.util.HashMap;
import java.util.Map;

/**
 * @description 编号分级的操作类
 * @author stm
 */
public class DataStru {

	private final String stru;
	private int struJs;
	private char[] cstru;
	private final Map<Integer, Integer> jslenCache = new HashMap<>();
	private final Map<Integer, Integer> lenjsCache = new HashMap<>();

	public DataStru(String stru) {
		this.stru = stru;
		parseStru();
	}

	/**
	 * 获取此编码结构的最大级数
	 * 
	 * @return
	 */
	public int getMaxJs() {
		return struJs;
	}

	/**
	 * 根据当前编号的长度，获得此编号的级数
	 * 
	 * @param len
	 * @return
	 */
	public int getJsByLen(int len) {
		Integer js = lenjsCache.get(len);
		if (js != null) {
			return js;
		}
		int sum = 0;
		for (int i = 0; i < struJs; i++) {
			int d = Integer.parseInt(cstru[i] + "");
			sum = sum + d;
			if (sum == len) {
				lenjsCache.put(len, i + 1);
				return i + 1;
			}
		}
		throw new IllegalArgumentException(len + "不符合编码长度规范");
	}

	/**
	 * 根据级数获得此级数对应的编码长度
	 * 
	 * @param js
	 * @return
	 */
	public int getLenByJs(int js) {
		if (js > struJs || js <= 0) {
			throw new IllegalArgumentException(js + "不在级数范围内");
		}
		Integer sum = jslenCache.get(js);
		if (sum != null) {
			return sum;
		}
		sum = 0;
		for (int i = 0; i < js; i++) {
			int d = Integer.parseInt(cstru[i] + "");
			sum = sum + d;
		}
		jslenCache.put(js, sum);
		return sum;
	}

	/**
	 * 获取比str级数小的编码, 如果js<=0,返回str
	 * 
	 * @param str
	 * @param js
	 * @return
	 */
	public String getStr(String str, int js) {
		if (js <= 0 || str.length() <= getLenByJs(js)) {
			return str;
		}
		return str.substring(0, getLenByJs(js));
	}

	public String getParent(String str) {
		return getStr(str, getJsByLen(str.length()) - 1);
	}

	/**
	 * 获取str对应级数的编码 如getShortStr(10002001,2)=2001
	 * 
	 * @param str
	 * @param js
	 * @return
	 */
	public String getShortStr(String str, int js) {
		if (js <= 0) {
			return str;
		}
		return str.substring(getLenByJs(js - 1), getLenByJs(js));
	}

	/**
	 * 获取对应级数的长度 如1434的结构，三级的长度为3
	 * 
	 * @param js
	 * @return
	 */
	public int getJsLen(int js) {
		return Integer.parseInt(String.valueOf(cstru[js - 1]));
	}

	private void parseStru() {
		cstru = stru.toCharArray();
		struJs = cstru.length;
	}

	public String getStru() {
		return stru;
	}

	public static void main(String[] args) {
		// DataStru ds = new DataStru("1432");
		// System.out.println(ds.getLenByJs(3));
		// System.out.println(ds.getLenByJs(3));
		// System.out.println(ds.getLenByJs(3));
		//
		// System.out.println(ds.getJsByLen(8));
		// System.out.println(ds.getJsByLen(8));
		// System.out.println(ds.getJsByLen(8));
		// System.out.println(ds.getStr("123456789",3)) ;

		DataStru stru = new DataStru("4444");
		String columnValue = "A0020003";
		String value = stru.getParent(columnValue);
		System.out.println(value);
		System.out.println(stru.getLenByJs(1));
		System.out.println(stru.getShortStr(columnValue, 2));
	}

}
